import Bb from 'backbone';
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import Router from './components/Router.js';
import RootComponent from './views/RootComponent.js';
import Controller from './components/Controller.js';


const AppClass = Mn.Application.extend({
    channelName: 'priceStudyApp',
    radioEvents: {
        "navigate": 'onNavigate',
        "show:modal": "onShowModal",
        "product:delete": "onModelDelete",
        "discount:add": "onDiscountAdd",
        "discount:delete": "onModelDelete",
        "product:duplicate": "onProductDuplicate",
        "chapter:delete": "onModelDelete",
        "model:move:up": "onModelMoveUp",
        "model:move:down": "onModelMoveDown",
        "work:additem": "onWorkItemAdd",
        "workitem:edit": "onWorkItemEdit",
        "workitem:delete": "onModelDelete",
        "workitem:duplicate": "onWorkItemDuplicate",
        // product changed
        "product:changed": "onProductChanged",
        "reset:margin_rate": "onResetMarginRate",
    },
    radioRequests: {
        "insert:from:catalog": "onInsertFromCatalog"
    },
    onBeforeStart(app, options) {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.price_study = this.facade.request('get:model', 'price_study');
        this.chapters = this.facade.request('get:collection', 'price_study_chapters');
        this.discounts = this.facade.request('get:collection', 'discounts');
        const model = this.facade.request('get:model', 'display_options');

        this.rootView = new RootComponent({
            model: this.price_study,
            collection: this.chapters,
            section: options['section']
        });
        this.controller = new Controller({
            rootView: this.rootView,
            priceStudy: this.price_study,
            chapters: this.chapters,
            section: options['section']
        })
        this.listenTo(model, 'saved:display_units', () => this.onNavigate('index'));
        new Router({
            controller: this.controller
        });
    },
    onStart(app, options) {
        this.showView(this.rootView);

    },
    onNavigate(route_name, parameters) {
        let dest_route = route_name;
        if (!_.isUndefined(parameters)) {
            dest_route += "/" + parameters;
        }
        window.location.hash = dest_route;
        Bb.history.loadUrl(dest_route);
    },
    onModelDelete(model) {
        const promise = this.controller.modelDelete(model);
        if (promise) {
            promise.then(() => this.onProductChanged(null));
        }
    },
    onProductDuplicate(product, chapterId) {
        this.controller.duplicateProduct(product, chapterId);
    },
    onWorkItemAdd(workModel) {
        this.controller.addWorkItem(workModel);
    },
    onWorkItemEdit(model) {
        this.controller.editWorkItem(model);
    },
    onWorkItemDuplicate(model) {
        this.controller.duplicateWorkItem(model);
    },
    onModelMoveUp(model) {
        this.controller.moveUp(model);
    },
    onModelMoveDown(model) {
        this.controller.moveDown(model);
    },
    onInsertFromCatalog(collection, sale_products) {
        return this.controller.insertFromCatalog(collection, sale_products);
    },
    onProductChanged(product) {
        $.when([
            this.price_study.fetch(),
            this.chapters.fetch(),
            this.discounts.fetch()
        ]).then(
            () => {
                window.location.hash = "#index";
                this.facade.trigger('changed:task');
            }
        );
    },
    onResetMarginRate() {
        this.controller.resetMarginRate();
    },
    onDiscountAdd() {
        this.controller.addDiscount();
    }
});

export default AppClass;